/**
 * Created by ly on 2017/10/12.
 */
var hlUrlUtil = (function () {
  var urlUtil = {
    //*操作href参数*///
    GetQueryString: function(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
      var r = window.location.href.substr(window.location.href.indexOf('?') + 1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    },
		$query: function () {
			var url = location.href;
			var arr = []; //存储参数的数组
			var res = {}; //存储最终JSON结果对象
			arr = url.split("?")[1].split("&");
			for( let i = 0,len = arr.length; i<len; i++ ) {
				//如果有等号，则执行赋值操作
				if ( arr[i].indexOf("=")!=-1 ) {
					let str = arr[i].split("=");
					//str=[a,1];
					res[str[0]] = str[1];
				} else { //没有等号，则赋予空值
					res[arr[i]] = "";
				}
			}
			return res; //{"a": "1", "b": "2", "c": "test", "d": ""}
		},
    /**
     * 跳转页面
     * @param   {String} route 配置的路由名称
     * @param   {obj} parame   传参
     * @param   {boolean} isOpenPage 是否新开页面
     * @returns {String}
     */
    goTo:function (route,parame,isOpenPage) {
      var str = '';
      var isOpenPage = false || isOpenPage;

      if(parame){
        str = '?';
        for(i in parame){
          str += (i + '=' + parame[i] + '&')
        }
      }
      str = str.substring(0, str.lastIndexOf('&'));
      if(isOpenPage){
        window.open(window.location.protocol +'//' + window.location.host + window.location.pathname + '#/' + route + str)
      }
      if(!isOpenPage)return window.location.href = window.location.protocol +'//' + window.location.host + window.location.pathname + '#/' + route + str

    },
    /**
     * 不跳转url后添加参数
     * @param   {obj} parame   传参
     */
     addURLParam:function(parame){
       var url = window.location.href;
       var str = null;
       if(url.indexOf('?') >= 0){ str = '&' }
       if(url.indexOf('?') < 0){ str = '?' }
       if(parame){
         for(i in parame){
           // 没有原key值直接添加
           if(url.indexOf(i) === -1){ str += (i + '=' + parame[i] + '&')}
         }
         url += str.substring(0,str.length - 1)

         for(i in parame){
           // 有key值则替换对应key下的value值
           if (url.indexOf(i) >= 0) {
             var oldValue = i + '=' + escape(this.GetQueryString(i))
             var newValue = i + '=' + parame[i]
             url = url.replace(oldValue,newValue)
           }
         }
       }
       history.pushState('','',url)
     }
  }

  return urlUtil
}())
